<template>
  <div class="app-container">
    <!-- 查询 -->
    <el-row>
      <el-col class="mb-2">
        <el-form-item style="flex: 1" label="任务名称">
          <el-input v-model="query.task_name" class="ya-search-value" placeholder="查询内容" clearable />
          <el-form-item label="任务状态" style="margin-left: 15px; width: 200px">
            <el-select v-model="query.task_status" placeholder="任务状态">
              <el-option :value="2" label="进行中" />
              <el-option :value="3" label="已完成" />
              <el-option :value="1" label="未完成" />
              <el-option :value="4" label="未开始" />
            </el-select>
          </el-form-item>
          <el-button type="primary" title="查询/刷新" style="margin-left: 10px" @click="search()">查询</el-button>
          <el-button type="default" title="重置查询条件" @click="refresh()">重置</el-button>
          <!-- <el-button type="primary" @click="add()">添加</el-button> -->
        </el-form-item>
      </el-col>
    </el-row>
    <el-dialog
      v-model="selectDialog"
      :title="selectTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      top="20vh"
    >
      <el-form ref="selectRef" label-width="120px">
        <el-form-item v-if="selectType === 'editcate'" label="分类">
          <el-cascader
            v-model="category_ids"
            :options="categoryData"
            :props="categoryProps"
            class="w-full"
            clearable
            filterable
          />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'edittag'" label="标签">
          <el-select v-model="tag_ids" multiple clearable filterable class="w-full">
            <el-option v-for="item in tagData" :key="item.tag_id" :label="item.tag_name" :value="item.tag_id" />
          </el-select>
        </el-form-item>
        <el-form-item v-else-if="selectType === 'istop'" label="是否置顶">
          <el-switch v-model="is_top" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'ishot'" label="是否热门">
          <el-switch v-model="is_hot" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'isrec'" label="是否推荐">
          <el-switch v-model="is_rec" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'disable'" label="是否禁用">
          <el-switch v-model="is_disable" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'release'" label="发布时间">
          <el-date-picker v-model="end_date" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item v-else-if="selectType === 'dele'">
          <span class="c-red">确定要删除选中的{{ task_name }}吗？</span>
        </el-form-item>
        <el-form-item :label="task_name + 'ID'">
          <el-input v-model="selectIds" type="textarea" autosize disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :loading="loading" @click="selectCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="selectSubmit">提交</el-button>
      </template>
    </el-dialog>
    <!-- 列表 -->
    <el-table
      ref="table"
      v-loading="loading"
      :data="data"
      :height="height"
      @sort-change="sort"
      @selection-change="select"
    >
      <el-table-column type="selection" width="42" title="全选/反选" />
      <el-table-column prop="task_name" label="任务名称" min-width="175" show-overflow-tooltip />
      <el-table-column prop="task_status" label="任务状态" min-width="105" show-overflow-tooltip>
        <!-- 自定义插槽内容 -->
        <template #default="{ row }">
          <!-- 判断任务状态，返回不同的显示内容 -->
          <span v-if="row.task_status == '1'"> 未完成 </span>
          <span v-if="row.task_status == '2'"> 进行中</span>
          <span v-if="row.task_status == '3'"> 已完成</span>
          <span v-if="row.task_status == '4'"> 未开始 </span>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建日期" width="165" sortable="custom" />
      <el-table-column prop="end_date" label="截止日期" width="165" sortable="custom" />
      <el-table-column label="操作" width="165">
        <template #default="scope">
          <el-link type="primary" class="mr-1" :underline="false" @click="fenpei(scope.row)"> 任务分配 </el-link>
          <!-- <el-link type="primary" class="mr-1" :underline="false" @click="edit(scope.row)"> 修改 </el-link>
          <el-link type="primary" :underline="false" @click="selectOpen('dele', [scope.row])"> 删除 </el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="count > 0"
      v-model:total="count"
      v-model:page="query.page"
      v-model:limit="query.limit"
      @pagination="list"
    />
    <!-- 添加修改 -->
    <el-dialog
      v-model="dialog"
      :title="dialogTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancel"
      top="5vh"
      width="1200px"
    >
      <el-form ref="ref" :rules="rules" :model="model" label-width="120px">
        <el-scrollbar native :height="height - 80">
          <el-form-item label="任务名称" prop="task_name">
            <el-input v-model="model.task_name" placeholder="请输入任务名称" clearable />
          </el-form-item>
          <el-form-item style="width: 100%" label="截止时间" prop="end_date">
            <el-date-picker
              v-model="model.end_date"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date(2024, 1, 1, 0, 0, 0)"
              placeholder="截止时间"
            />
          </el-form-item>
          <!-- <el-form-item label="任务成员" prop="user_id_list">
            <el-select v-model="model.user_id_list" placeholder="任务状态">
              <el-option value="成员1" label="成员1" />
              <el-option value="成员2" label="成员2" />
              <el-option value="成员3" label="成员3" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="任务状态" prop="task_status">
            <el-select v-model="model.task_status" placeholder="任务状态">
              <el-option :value="2" label="进行中" />
              <el-option :value="3" label="已完成" />
              <el-option :value="1" label="未完成" />
              <el-option :value="4" label="未开始" />
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="task_detail">
            <RichEditor v-model="model.task_detail" />
          </el-form-item>
        </el-scrollbar>
      </el-form>
      <template #footer>
        <el-button :loading="loading" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
    <!-- 任务分配 -->
    <el-dialog
      v-model="fenpeidialog"
      :title="'任务分配'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancel"
      style="height: 700px"
      top="5vh"
    >
      <el-scrollbar height="590px">
        <div class="divpad">任务名称：{{ fenpeidata.task_name }}</div>
        <!-- <div>团队介绍：{{ fenpeidata.team_introduce }}</div> -->
        <div class="divpad">任务创建时间：{{ fenpeidata.create_time }}</div>
        <div class="divpad">任务截止时间：{{ fenpeidata.end_date }}</div>
        <el-form-item disabled label="任务描述：" prop="task_detail">
          <RichEditor v-model="fenpeidata.task_detail" />
        </el-form-item>
        <el-form-item label="指派成员：" prop="user_id">
          <el-select v-model="fenpeidata.user_id" placeholder="指派成员 ">
            <el-option v-for="item in userListSelect" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-scrollbar>
      <div style="display: flex; justify-content: center">
        <el-button :loading="loading" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="feipeisubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination/index.vue'
import RichEditor from '@/components/RichEditor/index.vue'
import { arrayColumn } from '@/utils/index'
import { getPageLimit } from '@/utils/settings'
import { list, add, edit, dele, info, userlist, taskFenpei } from '@/api/test/test'

export default {
  task_name: 'ContentContent',
  components: { Pagination, RichEditor },

  data() {
    return {
      percentage: 20,
      customColor: '#409eff',
      customColors: [
        { color: '#f56c6c', percentage: 20 },
        { color: '#e6a23c', percentage: 40 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 80 },
        { color: '#6f7ad3', percentage: 100 }
      ],
      // -------------------
      task_name: '内容',
      height: 680,
      loading: false,
      idkey: 'task_id',
      exps: [{ exp: 'like', task_name: '包含' }],
      query: {
        page: 1,
        limit: getPageLimit(),
        task_name: '', // 任务名称
        task_status: '', // 任务状态
        task_detail: '', // 任务状态
        user_id_list: '', // 任务人员
        // user_id: Number(localStorage.getItem('userID'))
        // search_field: 'task_name',
        // search_exp: 'like',
        // date_field: 'create_time'
      },
      data: [],
      userListSelect: [],
      count: 0,
      dialog: false,
      fenpeidialog: false,
      fenpeidata: {},
      infodialog: false,
      dialogTitle: '',
      model: {
        id: '',
        task_name: '', // 任务名称
        task_status: '', // 任务状态
        task_detail: '', // 任务状态
        user_id_list: '', // 任务人员
        jindu:60,
        // content_id: '',
        // unique: '',
        // category_ids: [],
        // tag_ids: [],
        // image_id: 0,
        // image_url: '',
        // task_name: '',
        // title: '',
        // keywords: '',
        // description: '',
        // content: '',
        // source: '',
        // author: '',
        // url: '',
        // remark: '',
        // sort: 250,
        // hits: 0,
        // hits_initial: 0,
        // images: [],
        // videos: [],
        // audios: [],
        // words: [],
        // others: []
      },
      rules: {
        task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        task_status: [{ required: true, message: '请选择任务状态', trigger: 'change' }],
        end_date: [{ required: true, message: '请选择发布时间', trigger: 'change' }]
      },
      tagData: [],
      categoryData: [],
      categoryProps: {
        checkStrictly: true,
        value: 'category_id',
        label: 'category_name',
        multiple: true,
        emitPath: false
      },
      selection: [],
      selectIds: '',
      selectTitle: '操作',
      selectDialog: false,
      selectType: '',
      category_ids: [],
      tag_ids: [],
      is_top: 0,
      is_hot: 0,
      is_rec: 0,
      is_disable: 0,
      end_date: ''
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
    this.userlist()
  },
  methods: {
    // 进度条颜色变化
    customColorMethod(percentage) {
      if (percentage < 30) {
        return '#909399'
      } else if (percentage < 70) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    increase() {
      this.percentage += 10
      if (this.percentage > 100) {
        this.percentage = 100
      }
    },
    decrease() {
      this.percentage -= 10
      if (this.percentage < 0) {
        this.percentage = 0
      }
    },
    // 用户列表
    userlist() {
      this.loading = true
      userlist({ page: 1, type: '1', limit: getPageLimit() })
        .then((res) => {
          res.data.forEach((ele, index) => {
            console.log(ele, 'userlist')
            this.userListSelect.push({
              value: ele.user_id,
              label: ele.nickname
            })
          })
          console.log(this.userListSelect, 'userlist')
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 列表
    list() {
      this.loading = true
      list(this.query)
        .then((res) => {
          this.data = res.data.list
          this.count = res.data.count
          this.categoryData = res.data.category
          this.tagData = res.data.tag
          this.exps = res.data.exps
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 添加修改
    add() {
      this.dialog = true
      this.dialogTitle = this.task_name + '添加'
      this.reset()
    },
    // 任务分配
    fenpei(row) {
      this.fenpeidialog = true
      this.dialogTitle = '任务分配'
      var id = {}
      id[this.idkey] = row[this.idkey]
      info(id)
        .then((res) => {
          // this.reset(res.data)
          this.fenpeidata = res.data
          console.log(this.fenpeidata)
        })
        .catch(() => {})
    },
    feipeisubmit() {
      taskFenpei({
        id: this.fenpeidata.task_id,
        task_name: this.fenpeidata.task_name,
        user_id: this.fenpeidata.user_id
      })
        .then((res) => {
          // this.reset(res.data)
          // this.fenpeidata = res.data
          ElMessage.success(res.msg)
          this.cancel()
          console.log(this.fenpeidata)
        })
        .catch(() => {})
    },
    edit(row) {
      this.dialog = true
      this.dialogTitle = this.task_name + '修改：' + row[this.idkey]
      var id = {}
      id[this.idkey] = row[this.idkey]
      info(id)
        .then((res) => {
          this.reset(res.data)
        })
        .catch(() => {})
    },
    cancel() {
      this.dialog = false
      this.fenpeidialog = false
      this.infodialog = false
      this.reset()
    },
    submit() {
      this.$refs['ref'].validate((valid) => {
        if (valid) {
          if (this.model[this.idkey]) {
            edit(this.model)
              .then((res) => {
                this.list()
                this.dialog = false
                ElMessage.success(res.msg)
              })
              .catch(() => {})
          } else {
            add(this.model)
              .then((res) => {
                this.list()
                this.dialog = false
                ElMessage.success(res.msg)
              })
              .catch(() => {})
          }
        } else {
          ElMessage.error('请完善必填项（带红色星号*）')
        }
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['ref'] !== undefined) {
        try {
          this.$refs['ref'].resetFields()
          this.$refs['ref'].clearValidate()
        } catch (error) {}
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 重置查询
    refresh() {
      const limit = this.query.limit
      this.query = this.$options.data().query
      this.$refs['table'].clearSort()
      this.query.limit = limit
      this.list()
    },
    // 排序
    sort(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },
    // 操作
    select(selection) {
      this.selection = selection
      this.selectIds = this.selectGetIds(selection).toString()
    },
    selectGetIds(selection) {
      return arrayColumn(selection, this.idkey)
    },
    selectAlert() {
      ElMessageBox.alert('请选择需要操作的' + this.task_name, '提示', {
        type: 'warning',
        callback: () => {}
      })
    },
    selectOpen(selectType, selectRow = '') {
      if (selectRow) {
        this.$refs['table'].clearSelection()
        const selectRowLen = selectRow.length
        for (let i = 0; i < selectRowLen; i++) {
          this.$refs['table'].toggleRowSelection(selectRow[i], true)
        }
      }
      if (!this.selection.length) {
        this.selectAlert()
      } else {
        this.selectTitle = '操作'
        if (selectType === 'editcate') {
          this.selectTitle = this.task_name + '修改分类'
        } else if (selectType === 'edittag') {
          this.selectTitle = this.task_name + '修改标签'
        } else if (selectType === 'istop') {
          this.selectTitle = this.task_name + '是否置顶'
        } else if (selectType === 'ishot') {
          this.selectTitle = this.task_name + '是否热门'
        } else if (selectType === 'isrec') {
          this.selectTitle = this.task_name + '是否推荐'
        } else if (selectType === 'disable') {
          this.selectTitle = this.task_name + '是否禁用'
        } else if (selectType === 'release') {
          this.selectTitle = this.task_name + '发布时间'
        } else if (selectType === 'dele') {
          this.selectTitle = this.task_name + '删除'
        }
        this.selectDialog = true
        this.selectType = selectType
      }
    },
    selectCancel() {
      this.selectDialog = false
    },
    selectSubmit() {
      if (!this.selection.length) {
        this.selectAlert()
      } else {
        const selectType = this.selectType
        if (selectType === 'editcate') {
          this.editcate(this.selection)
        } else if (selectType === 'edittag') {
          this.edittag(this.selection)
        } else if (selectType === 'istop') {
          this.istop(this.selection, true)
        } else if (selectType === 'ishot') {
          this.ishot(this.selection, true)
        } else if (selectType === 'isrec') {
          this.isrec(this.selection, true)
        } else if (selectType === 'disable') {
          this.disable(this.selection, true)
        } else if (selectType === 'release') {
          this.release(this.selection, true)
        } else if (selectType === 'dele') {
          this.dele(this.selection)
        }
        this.selectDialog = false
      }
    },
    // 修改分类
    editcate(row) {
      editcate({
        ids: this.selectGetIds(row),
        category_ids: this.category_ids
      })
        .then((res) => {
          this.list()
          ElMessage.success(res.msg)
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 修改标签
    edittag(row) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        edittag({
          ids: this.selectGetIds(row),
          tag_ids: this.tag_ids
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    // 是否置顶
    istop(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_top = row[0].is_top
        if (select) {
          is_top = this.is_top
        }
        istop({
          ids: this.selectGetIds(row),
          is_top: is_top
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否热门
    ishot(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_hot = row[0].is_hot
        if (select) {
          is_hot = this.is_hot
        }
        ishot({
          ids: this.selectGetIds(row),
          is_hot: is_hot
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否推荐
    isrec(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_rec = row[0].is_rec
        if (select) {
          is_rec = this.is_rec
        }
        isrec({
          ids: this.selectGetIds(row),
          is_rec: is_rec
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 是否禁用
    disable(row, select = false) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        var is_disable = row[0].is_disable
        if (select) {
          is_disable = this.is_disable
        }
        disable({
          ids: this.selectGetIds(row),
          is_disable: is_disable
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 发布时间
    release(row) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        release({
          ids: this.selectGetIds(row),
          end_date: this.end_date
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.list()
          })
      }
    },
    // 删除
    dele(row) {
      if (!row.length) {
        this.selectAlert()
      } else {
        this.loading = true
        dele({
          ids: this.selectGetIds(row)
        })
          .then((res) => {
            this.list()
            ElMessage.success(res.msg)
          })
          .catch(() => {
            this.loading = false
          })
      }
    }
  }
}
</script>
<style>
.el-date-editor.el-input,
.el-date-editor.el-input__wrapper {
  width: 100%;
}

.divpad {
  padding: 10px 0;
}
</style>
